import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  Query,
  HttpCode,
  HttpStatus,
  UseGuards,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
  ApiBody,
} from '@nestjs/swagger';
import { NewsService } from './news.service';
import type { News } from './news.service';

@ApiTags('旅游资讯')
@Controller('news')
export class NewsController {
  constructor(private readonly newsService: NewsService) {}

  @ApiOperation({ summary: '获取资讯列表' })
  @ApiResponse({ status: 200, description: '成功获取资讯列表' })
  @Get()
  findAll(): News[] {
    return this.newsService.findAll();
  }

  @ApiOperation({ summary: '根据ID获取资讯详情' })
  @ApiResponse({ status: 200, description: '成功获取资讯详情' })
  @ApiResponse({ status: 404, description: '资讯不存在' })
  @Get(':id')
  findOne(@Param('id') id: string): News {
    const news = this.newsService.findById(id);
    if (news) {
      this.newsService.incrementViews(id);
    }
    if (!news) {
      throw new Error('News not found');
    }
    return news;
  }

  @ApiOperation({ summary: '创建资讯' })
  @ApiResponse({ status: 201, description: '资讯创建成功' })
  @ApiBearerAuth()
  @ApiBody({ type: () => Object, description: '资讯数据' })
  @Post()
  @HttpCode(HttpStatus.CREATED)
  create(@Body() newsData: Omit<News, 'id' | 'views' | 'createdAt' | 'updatedAt'>): News {
    return this.newsService.create(newsData);
  }

  @ApiOperation({ summary: '更新资讯' })
  @ApiResponse({ status: 200, description: '资讯更新成功' })
  @ApiResponse({ status: 404, description: '资讯不存在' })
  @ApiBearerAuth()
  @ApiBody({ type: () => Object, description: '资讯更新数据' })
  @Put(':id')
  update(
    @Param('id') id: string,
    @Body() newsData: Partial<Omit<News, 'id' | 'createdAt'>>,
  ): News {
    const result = this.newsService.update(id, newsData);
    if (!result) {
      throw new Error('News not found');
    }
    return result;
  }

  @ApiOperation({ summary: '删除资讯' })
  @ApiResponse({ status: 204, description: '资讯删除成功' })
  @ApiResponse({ status: 404, description: '资讯不存在' })
  @ApiBearerAuth()
  @Delete(':id')
  @HttpCode(HttpStatus.NO_CONTENT)
  remove(@Param('id') id: string): void {
    const result = this.newsService.delete(id);
    if (!result) {
      throw new Error('News not found');
    }
  }
}